package com.bawei.module_mall.ui.goodsshow

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseMVIFragment
import com.bawei.module_mall.databinding.FragmentMyGoodsShowBinding
import com.bawei.module_mall.http.viewModel.ShopViewModel
import com.bawei.module_mall.adapter.GoodsAdapter
import com.bawei.module_mall.http.intent.ShopIntent
import com.bawei.module_mall.http.state.ShopState
import kotlinx.coroutines.launch

class MyGoodsShowFragment : BaseMVIFragment() {
    private val binding: FragmentMyGoodsShowBinding by lazy {
        FragmentMyGoodsShowBinding.inflate(layoutInflater)
    }
    private lateinit var viewModel: ShopViewModel
    
    // 数据更新回调
    var onDataUpdated: (() -> Unit)? = null

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this)[ShopViewModel::class.java]
    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View = binding.root

    private val goodsAdapter: GoodsAdapter by lazy {
        GoodsAdapter(
            onItemClick = { item ->
                // 商品点击逻辑
                ARouter.getInstance().build(Router.Ui.SHOP_DETAIL_ACTIVITY)
                    .withInt("shopId", item.id.toInt()).navigation()
            }
            // showAddButton默认false，不传即可
        )
    }

    override fun initView() {
        binding.rvGoods.layoutManager = GridLayoutManager(requireActivity(), 2)

        binding.rvGoods.adapter = goodsAdapter
        
        // 设置嵌套滚动行为，支持与AppBarLayout的协调滚动
        binding.rvGoods.isNestedScrollingEnabled = true
        
        // 确保RecyclerView能够正确与AppBarLayout协调滚动
        binding.rvGoods.setHasFixedSize(true)
    }

    override fun lazyLoad() {
        lifecycleScope.launchWhenStarted {
            viewModel.intents.send(ShopIntent.ViewShowedGoods)
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            viewModel.state.collect {
                when (it) {
                    is ShopState.ViewShowedGoodsSuccess -> {
                        Log.d("MyGoodsShowFragment", "收到数据，数量=${it.goodsList?.size}")
                        val goodsList = it.goodsList
                        if (goodsList.isNullOrEmpty()) {
                            binding.rvGoods.visibility = View.GONE
                        } else {
                            binding.rvGoods.visibility = View.VISIBLE
                            goodsAdapter.submitList(goodsList)
                        }
                        // 通知Activity更新tab数量
                        onDataUpdated?.invoke()
                        Log.d("MyGoodsShowFragment", "数据更新完成，通知Activity更新tab数量")
                    }
                    is ShopState.Loading, is ShopState.Error -> {
                        binding.rvGoods.visibility = View.GONE
                    }
                    else -> {}
                }
            }
        }
    }

    // 新增：刷新"我的"商品列表
    fun refreshData() {
        // 重新请求"我的"商品数据
        lifecycleScope.launch {
            viewModel.intents.send(ShopIntent.ViewShowedGoods)
        }
    }
    
    // 获取商品数量
    fun getGoodsCount(): Int {
        return goodsAdapter.getCurrentList().size
    }

    fun isReady(): Boolean = isAdded && view != null && ::viewModel.isInitialized
}